/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.hnilica.cisteniulic.postgres;

import java.io.Serializable;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

/**
 *
 * @author swosh
 */
public class IntArrayHibernate implements UserType{

    @Override
    public int[] sqlTypes() {
        return new int[] {Types.ARRAY};
    }

    @Override
    public Class returnedClass() {
        return int[].class;
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        if( x == y)
            return true;
        if( null == x || null == y )
            return false;
        Class javaClass = returnedClass();
        if( ! javaClass.equals( x.getClass() ) || ! javaClass.equals( y.getClass() ) )
              return false;

        return x.equals( y );
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException     {
      IntArray intArray =  (IntArray) rs.getArray(names[0]);
        if( rs.wasNull() )
              return null;

        return intArray.getArray();
    }
    @Override
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
        if( null == value )
            preparedStatement.setNull(index, Types.INTEGER);
        else
              preparedStatement.setArray(index, new IntArray(value));

    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
    return value;
    }


    public Object realDeepCopy(Object value) throws HibernateException {
        return new IntArray(value);
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable)realDeepCopy(value);
    }

    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return realDeepCopy(cached);
    }

    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return realDeepCopy(original);
    }

}
